<?php
/**
 * Created by PhpStorm.
 * User: Hongjw
 * Date: 2018/3/18
 * Time: 19:48
 */

namespace App\Tools\File;



use App\Tools\Common\ComCheckCode;
use Illuminate\Http\Request;
use Storage;

class FileUpload
{
    /**
     * 上传文件
     * @param Request $request
     * @param $newFileName
     * @param string $path
     * @return array
     */
    public function postFileupload(Request $request,$newFileName,$path = 'app/'){
        //判断请求中是否包含name=file的上传文件
        if(!$request->hasFile('file')){
            return ComCheckCode::failRes('上传文件为空');
        }
        $file = $request->file('file');
        //判断文件上传过程中是否出错
        if(!$file->isValid()){
            return ComCheckCode::failRes('文件上传出错');
        }
        if($newFileName){
            $newFileName = md5(time().rand(0,10000)).'.'.$file->getClientOriginalExtension();
        }else{
            $newFileName .= '.'.$file->getClientOriginalExtension();
        }

        $savePath = $path.$newFileName;
        $bytes = Storage::put(
            $savePath,
            file_get_contents($file->getRealPath())
        );
        if(!Storage::exists($savePath)){
            return ComCheckCode::failRes('保存文件失败');
        }
        //header("Content-Type: ".Storage::mimeType($savePath));
        //echo Storage::get($savePath);
        return ComCheckCode::successRes(compact('savePath','newFileName','path'));
    }
}